package edu.zzuli.assistant.api.action;

import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import edu.zzuli.assistant.bean.News;
import edu.zzuli.assistant.bean.User;
import edu.zzuli.assistant.service.NewsService;
import edu.zzuli.assistant.service.impl.NewsServiceImpl;
import edu.zzuli.assistant.until.StrUtil;

public class NewsAction extends ActionSupport implements ModelDriven ,SessionAware{
	
	private NewsService newsService = new NewsServiceImpl();
	private Map<String, Object> session;
	private List <News> newsList;
	private News news;
	private String[] fields = {"id","title","content","newsPics","postTime","authorName"};
	private String[] fieldUser = {"id","title","content","newsPics","postTime","authorName","user"};
	private String[] clazzFields = {"id","headUrl"};
	
	private int page =1;//评论当前页数 默认第一页

	public int getPage() {
		return page;
	}
	public void setPage(int page) {
		this.page = page;
	}
	public News getNews() {
		return news;
	}

	public void setNews(News news) {
		this.news = news;
	}
	public Map<String, Object> getSession() {
		return session;
	}
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}
	@Override
	public Object getModel() {
		// TODO Auto-generated method stub
	       if(news == null){
	    	   news = new News();
	       }
	     return news;
	}
	
	//用户没有登录  去除最近发布news (news_latest.action)
	public void latest(){
		newsList=newsService.getNewsList(page, 10);
		StrUtil.sendJson(News.class, fieldUser, User.class, clazzFields , newsList);
	}

	//某个用户所发的news
	public void person(){
		if(news.getUser().getId()!=null){
			newsList=newsService.getSelfNews(news.getUser().getId(), page, 10);
			StrUtil.sendJson(News.class, fields, newsList);
		}
		else{
			StrUtil.sendMsg(ERROR);
		}
	}
	// 关注的人的 news (news_follow.action)
	public void follow() {
		if (session.get("userId") != null) {
			String userId = session.get("userId").toString();
			newsList = newsService.getFollowNews(userId, page, 8);
			StrUtil.sendJson(News.class, fields, newsList);
		}
		else{
			StrUtil.sendMsg(LOGIN);
		}
	}
	
	//发布news
	public void send() {
		if (session.get("userId") != null
				&& Short.parseShort((session.get("status").toString())) != User.STATUS_STUDENT) {
			User user = new User();
			user.setId(session.get("userId").toString());
			news.setUser(user);
			news.setAuthorName(session.get("userName").toString());
			news.setPostTime(new Date());
			if (news.getTitle()== null || news.getTitle().length() > 35) {
				StrUtil.sendMsg(ERROR);
			}
			else{
				if(new NewsServiceImpl().PublishNews(news)){
					StrUtil.sendMsg(SUCCESS);
				}
				else{
					StrUtil.sendMsg("fail");
				}
			}
		} else {
			// 没有登录 跳转到首页
			StrUtil.sendMsg(LOGIN);
		}
		
	}

}
